package com.example.springboot_redis.controller;

import com.example.springboot_redis.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author shishuqian
 * date 2021/3/20
 * time 13:16
 **/
@RestController
@RequestMapping("/redis")
public class StudentHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/set/{key}")
    public void set(@PathVariable("key") String key, @RequestBody Student student){
        redisTemplate.opsForValue().set(key,student);
    }

    @GetMapping("/get/{key}")
    public Student get(@PathVariable("key") String key){
        return (Student)redisTemplate.opsForValue().get(key);
    }

    @DeleteMapping("/delete/{key}")
    public boolean delete(@PathVariable("key") String key){
        redisTemplate.delete(key);
        return redisTemplate.hasKey(key);
    }

    @GetMapping("/list")
    public List<String> listTest(){
        ListOperations<String,String> listOperations = redisTemplate.opsForList();
        listOperations.leftPush("list","hello");
        listOperations.leftPush("list","world");
        listOperations.leftPush("list","java");
        List<String> list = listOperations.range("list",0,2);
        return list;
    }

    @GetMapping("/set")
    public Set<String> setTest(){
        SetOperations<String,String> setOperations = redisTemplate.opsForSet();
        setOperations.add("set","Hello");
        setOperations.add("set","SetTest");
        setOperations.add("set","Java");
        Set<String> set = setOperations.members("set");
        return set;
    }

    @GetMapping("/zset")
    public Set<String> zsetTest(){
       ZSetOperations<String,String> zSetOperations = redisTemplate.opsForZSet();
       zSetOperations.add("zset","hello",1);
        zSetOperations.add("zset","world2",2);
        zSetOperations.add("zset","java3",3);
        Set<String> set = zSetOperations.range("zset",0,2);
        return set;
    }

    @GetMapping("/hash")
    public void hash(){
       HashOperations<String,String,String> hashOperations = redisTemplate.opsForHash();
       hashOperations.put("key","hashKey","value");
        System.out.println(hashOperations.get("key","hashKey"));
    }
}
